/**
 * BrandBigData.com Inc. Copyright (c) 2016 All Rights Reserved.
 */
package com.qibao.toolkit;

import com.qibao.toolkit.util.PythonUtils;
import com.qibao.toolkit.exception.PythonExecuteException;
import com.qibao.toolkit.exception.PythonSyntaxException;
import com.qibao.toolkit.facade.ExecuteContext;
import com.qibao.toolkit.facade.PythonExecutorService;
import java.util.List;
import org.apache.commons.lang3.StringUtils;

/**
 * @author xumin
 * @version $Id:PythonExecutorServiceImpl.java, v0.1 2017/7/1 17:21 xumin
 */
public class LocalPythonExecutorService implements PythonExecutorService {

    private PythonExecutorPool pythonExecutorPool;

    public LocalPythonExecutorService(PythonExecutorPool pythonExecutorPool) {
        this.pythonExecutorPool = pythonExecutorPool;
    }

    @Override
    public String executeScript(String script, ExecuteContext executeContext)
            throws PythonExecuteException {
        try {
            PythonExecutor pythonExecutor = pythonExecutorPool.borrowObject();
            try {
                script = replaceVariables(script);
                return pythonExecutor.executeScript(script, executeContext);
            } finally {
                pythonExecutorPool.returnObject(pythonExecutor);
            }
        } catch (Exception e) {
            throw new PythonExecuteException(e.getMessage(), e);
        }
    }

    private String replaceVariables(String script) {
        List<String> variables = PythonUtils.extractVariables(script);
        for (String variable : variables) {
            script = StringUtils.replace(script, "{" + variable + "}", variable);
        }
        return script;
    }

    @Override
    public List<String> extractVariables(String script) throws PythonSyntaxException {
        return PythonUtils.extractVariables(script);
    }

}
